<template>
  <el-input
    @keyup.enter="handleEnter"
    style="height: 0px; width: 0px; z-index: -999; position: absolute"
    ref="payCodeRef"
    v-model="payCode"
    @blur="handleIptBlur"
  ></el-input>
  <!-- <input ref="payCodeRef" v-model="payCode"/> -->
  <div class="content-layout">
    <div class="header-layout">
      <div class="complete-title-layout">
        <img src="../../../assets/images/order/ic_wait.png" alt="" srcset="" />
        <h5
          style="
            margin-left: 0.5vw;
            font-family: PingFang SC, PingFang SC;
            font-weight: 800;
            font-size: 17px;
            color: #333333;
          "
        >
          待付款
        </h5>
      </div>
      <div class="info-layout">
        <div class="info-item-layout">
          <img src="../../../assets/images/order/ic_order_time.png" />
          <p class="title">下单时间</p>
          <p class="name">
            {{ timestampToTime(orderData.createtime as number) }}
          </p>
        </div>
      </div>
      <div class="info-layout">
        <div class="info-item-layout">
          <img src="../../../assets/images/order/ic_cashier.png" />
          <p class="title">收银员</p>
          <p class="name">{{ orderData.cashier.name }}</p>
        </div>
      </div>
    </div>

    <div class="main-layout">
      <div class="left-layout">
        <el-table
          :data="orderData.item"
          style="width: 100%; height: calc(100vh - 22.5vh); border-radius: 6px"
        >
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
          <el-table-column prop="goods_image" label="商品照片" width="120px">
            <template #="{ row, $index }">
              <img :src="row.goods_image" style="width: 46px; height: 46px" />
            </template>
          </el-table-column>
          <el-table-column prop="goods_title" label="商品名称" width="280px">
            <template #="{ row, $index }">
              <p
                style="
                  font-size: 14px;
                  color: #333333;
                  font-family: PingFang SC, PingFang SC;
                  font-weight: 800;
                "
              >
                {{ row.goods_title }}
              </p>
              <p
                style="
                  font-size: 11px;
                  color: #999999;
                  font-family: PingFang SC, PingFang SC;
                  font-weight: 400;
                  margin-top: 5px;
                "
              >
                规格：{{ row.goods_sku_text }}
              </p>
            </template>
          </el-table-column>

          <el-table-column
            prop="goods_num"
            label="数量"
            align="center"
            width="120px"
          >
            <template #="{ row, $index }">
              <p
                style="
                  font-size: 14px;
                  color: #333333;
                  font-family: PingFang SC, PingFang SC;
                  font-weight: bold;
                "
              >
                x{{ row.goods_num }}
              </p>
            </template>
          </el-table-column>

          <el-table-column prop="goods_price" label="单价(元）" align="center">
            <template #="{ row, $index }">
              <p
                style="
                  font-size: 14px;
                  color: #333333;
                  font-family: PingFang SC, PingFang SC;
                  font-weight: bold;
                "
              >
                {{ row.goods_price }}
              </p>
              <div class="vip_price flex_center">
                <div class="icon flex_center_center">会员价</div>
                <div class="vip_txt">{{ row.goods_vip_price }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="total" label="小计" align="center">
            <template #="{ row, $index }">
              <p
                style="
                  font-size: 14px;
                  color: #333333;
                  font-family: PingFang SC, PingFang SC;
                  font-weight: bold;
                "
              >
                {{
                  multiply(row.goods_num, Number.parseFloat(row.goods_price))
                }}
              </p>
              <div class="vip_price flex_center">
                <div class="icon flex_center_center">会员价</div>
                <div class="vip_txt">
                  {{
                    (
                      Number.parseFloat(row.goods_vip_price) * row.goods_num
                    ).toFixed(2)
                  }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="bottom-layout" v-if="false">
          <div>
            <el-button
              size="small"
              plain
              style="
                width: 93px;
                height: 33px;
                border: none;
                font-family: PingFang SC, PingFang SC;
                border-radius: 3px;
                border: 1px solid #d4d6d9;
                font-weight: bold;
                font-size: 14px;
                color: #666;
              "
              >挂单</el-button
            >

            <el-button
              size="small"
              plain
              style="
                width: 93px;
                height: 33px;
                border: none;
                font-family: PingFang SC, PingFang SC;
                border-radius: 3px;
                border: 1px solid #d4d6d9;
                font-weight: bold;
                font-size: 14px;
                color: #666;
              "
              >取单</el-button
            >
          </div>
          <div></div>
          <div>
            <el-button
              text
              style="font-size: 20px; font-weight: bold; color: #333"
              >￥{{ total }}</el-button
            >

            <el-popover
              placement="top-end"
              trigger="hover"
              effect="dark"
              :visible="popoverShow"
            >
              <div>
                <div
                  v-for="(item, index) in payList"
                  :key="index"
                  style="
                    display: flex;
                    padding: 15px 0px;
                    border-bottom: #999999 1px solid;
                  "
                  @click="payTypeClick(item.type)"
                >
                  <img
                    style="height: 20px; width: 20px"
                    :src="getImageUrl(item.icon)"
                    alt="加载失败"
                  />
                  <span
                    style="
                      text-align-last: justify;
                      width: 100%;
                      margin-left: 30px;
                    "
                  >
                    {{ item.name }}</span
                  >
                </div>
              </div>
              <template #reference>
                <el-button
                  @click="popoverShow = !popoverShow"
                  size="small"
                  plain
                  style="
                    background-color: #fd6013;
                    width: 93px;
                    height: 33px;
                    color: #fff;
                    font-weight: 400;
                    border: none;
                    font-family: PingFang SC, PingFang SC;
                    font-size: 14px;
                    color: #ffffff;
                  "
                  >结算({{ orderData.item.length }})</el-button
                >
              </template>
            </el-popover>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch } from "vue";
import { ElLoading, ElMessage } from "element-plus";
import {
  reqGetOrderDetails,
  reqPullPay,
  reqOrderStatus,
} from "../../../api/order/index";
import { useRoute } from "vue-router";
let route = useRoute();

import useOrderStore from "../../../store/modules/order";
let orderStore = useOrderStore();

const orderData = ref<any>({ cashier: {}, item: [] });
const total = ref<number>(0);
const payCode = ref<string>("");
const payCodeRef = ref();
const loading = ref();
const timer_2m = ref();
const timer_2s = ref();
const popoverShow = ref(false);

const payParam = ref({
  id: "",
  code: "vX7kYhyEVqOcFWJn",
  pay_type: "",
  auth_code: "",
});

const payStatusParam = ref({
  id: "",
  code: "vX7kYhyEVqOcFWJn",
});

const payList = reactive([
  {
    name: "现金",
    icon: "ic_cash.png",
    type: "cash",
  },
  {
    name: "微信",
    icon: "ic_wechat.png",
    type: "wx",
  },
  {
    name: "支付宝",
    icon: "ic_alipay.png",
    type: "zfb",
  },
  {
    name: "会员余额",
    icon: "ic_masonry.png",
    type: "vip",
  },
]);

const handleEnter = async () => {
  payParam.value.auth_code = payCode.value;
  let result = await reqPullPay(payParam.value);
  if (result.code != 1) {
    if (result.msg.includes("支付密码")) {
      timer_2m.value = setTimeout(() => {
        clearInterval(timer_2s.value);
        loading.value.close();
        ElMessage.error("订单超时未支付");
      }, 10 * 1000);

      timer_2s.value = setInterval(() => {
        getOrderStatus();
      }, 2000);
    }
  } else {
    loading.value.close();
  }
  payCode.value = "";
};

const getOrderStatus = async () => {
  let result = await reqOrderStatus(payStatusParam.value);
  if (result == 1) {
    loading.value.close();
    clearInterval(timer_2s.value);
    clearInterval(timer_2m.value);
    orderStore.modifyStatus(1);
  }
};

const handleIptBlur = async () => {
  await nextTick();
  if (payCodeRef.value) {
    payCodeRef.value.focus();
  }
};

const payTypeClick = async (type: string) => {
  payParam.value.pay_type = type;
  if (type != "cash") {
    payCodeRef.value.focus();
    loading.value = ElLoading.service({
      lock: true,
      text: "支付中...",
      background: "rgba(0, 0, 0, 0.7)",
    });
  } else {
    let result = await reqPullPay(payParam.value);
    if (result == 1) {
      orderStore.modifyStatus(1);
    }
  }
  popoverShow.value = false;
};

const paramOrderData = ref(route.params.orderData);

onMounted(() => {
  getOrderDetails();
});

const getOrderDetails = async () => {
  const id: any = route.query.id;
  let result = await reqGetOrderDetails(id, { code: "vX7kYhyEVqOcFWJn" });
  if (result.code == 1) {
    orderData.value = result.data;
    payParam.value.id = result.data.id as string;
    payStatusParam.value.id = result.data.id as string;
    if (orderData.value.item) {
      orderData.value.item.forEach((goods) => {
        total.value = Number.parseFloat(
          add(
            total.value,
            Number.parseFloat(
              multiply(goods.goods_num, Number.parseFloat(goods.goods_price))
            )
          )
        );
      });
    }
  }
};

/**
 * @动态本地图片
 */
const getImageUrl = (url: any) => {
  const path = new URL(`../../../assets/images/order/${url}`, import.meta.url);
  return path.href;
};

/**
 * @时间转换
 */
const timestampToTime = (timestamp: number) => {
  let date = new Date(timestamp * 1000);
  let Y = date.getFullYear() + "-";
  let M =
    (date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1) + "-";
  let D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
  let h =
    (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  let m =
    (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
    ":";
  let s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return Y + M + D + h + m + s;
};

/**
 * @加法
 */
const add = (arg1: number, arg2: number) => {
  let r1: number, r2: number, m: number, n: number;
  try {
    r1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  m = Math.pow(10, Math.max(r1, r2));
  n = r1 >= r2 ? r1 : r2;
  return ((arg1 * m + arg2 * m) / m).toFixed(n);
};

/**
 * @乘法
 */
const multiply = (arg1: number, arg2: number, digital = 2) => {
  let m = 0;
  let s1 = arg1.toString();
  let s2 = arg2.toString();
  let s1len = s1.split(".")[1] ? s1.split(".")[1].length : 0;
  let s2len = s2.split(".")[1] ? s2.split(".")[1].length : 0;
  m += s1len;
  m += s2len;
  return (
    (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
    Math.pow(10, m)
  )
    .toFixed(digital)
    .toString();
};
</script>

<style lang="scss" scoped>
@import "../../../assets/style/common.scss";

.content-layout {
  height: 100%;

  .header-layout {
    height: 95px;
    background: url("../../../assets/images/order/order_status_wait_bg.png")
      no-repeat;
    background-size: 100% 100%;
    display: flex;
    align-items: center;

    .complete-title-layout {
      display: flex;
      flex-direction: row;
      flex: 1.5;
      align-items: center;

      img {
        width: 22px;
        height: 22px;
        margin-left: 25px;
      }
    }

    .info-layout {
      flex: 1.2;

      .info-item-layout {
        display: flex;
        flex-direction: row;
        margin-bottom: 0.5vw;
        margin-top: 0.5vw;
        align-items: center;

        img {
          width: 17px;
          height: 17px;
        }

        .title {
          width: 4vw;
          font-family: PingFang SC, PingFang SC;
          font-weight: 400;
          font-size: 11px;
          color: #999999;
          margin-left: 5px;
        }

        .name {
          font-family: PingFang SC, PingFang SC;
          font-weight: 400;
          font-size: 11px;
          color: #333333;
        }
      }
    }
  }

  .main-layout {
    display: flex;
    flex-direction: row;
    margin-top: 1.5vh;

    .left-layout {
      flex: 1;
      background-color: white;
      border-radius: 6px;

      .bottom-layout {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        height: 67px;
        align-items: center;
        padding: 0px 20px;
        border-top: 0.5px #e6e8eb solid;
      }
    }
  }
}
</style>
